<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Hash;
use Vtiful\Kernel\Excel;

/**
 * 抽奖管理
 * Class DrawController
 * @package App\Http\Controllers\Admin
 */
class DrawController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:admin');
    }

    /**
     * 奖品列表
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index()
    {
        //查询用户游戏数据
        $drawData = DB::table('draw')
            ->orderBy('id', 'desc')
            ->get();

        return view('admin.draw.index', ['draw' => $drawData]);
    }

    /**
     * 修改奖品页面
     * @param $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit($id)
    {
        //查询游戏数据信息
        $draw = DB::table('draw')
            ->where('id', $id)
            ->first();

        return view('admin.draw.edit',[
            'draw'=>$draw
        ]);
    }

    /**
     * 修改奖品
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     * @throws \Illuminate\Validation\ValidationException
     */
    public function update(Request $request, $id)
    {
        //验证表单
        $this->validate($request, [
            'title' => ['nullable', 'string'],
            'rate' => ['nullable','numeric'],
            'is_luck' => ['required', 'numeric'],
            'money' => ['required','numeric'],
        ]);

        // 中奖率加起来不能超过一千
        $rateCount = DB::table('draw')->count('rate');
        if ($rateCount + $request->rate > 1000) {
            return response()->json(['message' => '中奖率不能超过一千', 'success' => 'false']);
        }

        //更新
        DB::table('draw')
            ->where('id', $id)
            ->update([
                'title' => $request->title,
                'rate' => $request->rate,
                'is_luck' => $request->is_luck,
                'money' => $request->money,
            ]);

        return response()->json(['message' => '编辑成功。', 'success' => 'true']);
    }

     /**
     * 抽奖记录
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
//     public function logIndex()
//     {
//         //查询用户游戏数据
//         $drawData = DB::table('draw_log')
//             ->select('draw_log.*', 'draw.title', 'users.username', 'users.unionid')
//             ->leftJoin('draw', 'draw_log.draw_id', '=', 'newdraw.id')
//             ->leftJoin('users', 'draw_log.user_id', '=', 'users.id')
//             ->where(function ($query) {
//                 if (!empty($_GET['is_luck']))
//                     $query->orWhere('draw_log.is_luck', '=', $_GET['is_luck']);
//                 if (!empty($_GET['status']))
//                     $query->orWhere('draw_log.status', '=', $_GET['status']);
//                 if (!empty($_GET['search']))
//                     $query->orWhere('users.unionid', '=', $_GET['search']);
//               })
//             ->where('game_num', '<>', '')
//             ->where('draw.id', '>', 0)
// //            ->orderBy('draw_log.status=2', 'desc')
//             ->orderBy('draw_log.id', 'desc')
//             ->paginate(15)
//             ->withPath('?status=' . @$_GET['status'] . '&is_luck='. @$_GET['is_luck']);

//         return view('admin.draw.log', ['draw' => $drawData]);
//     }
    public function logIndex()
    {
        //查询用户游戏数据
        $drawData = DB::table('draw_log')
            ->select('draw_log.*', 'newdraw.title', 'users.username', 'users.unionid')
            ->leftJoin('newdraw', 'draw_log.draw_id', '=', 'newdraw.id')
            ->leftJoin('users', 'draw_log.user_id', '=', 'users.id')
            ->where(function ($query) {
                if (!empty($_GET['is_luck']))
                    $query->orWhere('draw_log.is_luck', '=', $_GET['is_luck']);
                if (!empty($_GET['status']))
                    $query->orWhere('draw_log.status', '=', $_GET['status']);
                if (!empty($_GET['search']))
                    $query->orWhere('users.unionid', '=', $_GET['search']);
              })
            ->where('game_num', '<>', '')
            ->where('newdraw.id', '>', 0)
//            ->orderBy('draw_log.status=2', 'desc')
            ->orderBy('draw_log.id', 'desc')
            ->paginate(15)
            ->withPath('?status=' . @$_GET['status'] . '&is_luck='. @$_GET['is_luck']);

        return view('admin.draw.log', ['draw' => $drawData]);
    }

    /**
     * 处理中奖记录
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function handleDraw($id)
    {
        //更新
        DB::table('draw_log')
            ->where('id', $id)
            ->update([
                'status' => 1,
                'handle_time' => date("Y-m-d H:i:s"),
            ]);
        $this->sendWxTemplateMsg($id);
        return response()->json(['message' => '处理成功。', 'success' => 'true']);
    }

    /**
     * 处理刷号
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function shuaHao($id)
    {
        //更新
        DB::table('draw_log')
            ->where('id', $id)
            ->update([
                'status' => 1,
                'handle_time' => date("Y-m-d H:i:s"),
            ]);
        $this->sendWxTemplateMsg($id, 1, "请勿刷号！");
        return response()->json(['message' => '处理成功。', 'success' => 'true']);
    }

    /**
     * 反馈
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setMsg(Request $request)
    {
        $id = $request->id;
        $msg = $request->msg;
        if (!$id) {
            return response()->json(['message' => '请输入id', 'success' => 'false']);
        }
        if (!$msg) {
            return response()->json(['message' => '请输入反馈', 'success' => 'false']);
        }
        $log  = DB::table('draw_log')->where('id', $id)->first();
        if (!$log) {
            return response()->json(['message' => '没有记录', 'success' => 'false']);
        }
        if ($log->status != 2) {
            return response()->json(['message' => '记录状态错误', 'success' => 'false']);
        }
        DB::table('draw_log')->where('id', $id)->update(['status' => 3, 'msg'=>$msg]);
        $this->sendWxTemplateMsg($id,3, $msg);
        return response()->json(['message' => '反馈成功！', 'success' => 'true']);
    }

    public function sendWxTemplateMsg($id, $status = 1, $msg = '')
    {
        $row = DB::table('draw_log')
            ->where('id', $id)
            ->first();
        $user = DB::table('users')
            ->where('id', $row->user_id)
            ->first();
        sendRechargeWxTemplateMsg(
            $user->wx_unionid, $row->game_num, $row->game_url, $row->money * 1.01, $user->ly_balance
        );
    }


    /**
     * 兑换记录
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function dhLog()
    {
        //查询用户游戏数据
        $drawData = DB::table('draw_log')
            ->select('draw_log.*','users.username', 'users.unionid')
            ->leftJoin('users', 'draw_log.user_id', '=', 'users.id')
            ->where(function ($query) {
                if (!empty($_GET['status']))
                    $query->orWhere('draw_log.status', '=', $_GET['status']);
                if (!empty($_GET['unionid']))
                    $query->orWhere('users.unionid', '=', $_GET['unionid']);
                if (!empty($_GET['game_num']))
                    $query->orWhere('draw_log.game_num', 'like', "%{$_GET['game_num']}%");
            })
            ->where('game_num', '<>', '')
            ->where('draw_id',  0)
            ->orderBy('draw_log.id', 'desc')
            ->paginate(15)
            ->withPath('?status=' . @$_GET['status'] . '&unionid='. @$_GET['unionid'] . '&game_num='. @$_GET['game_num']);

        $gameIds = [];
        foreach ($drawData as $item) {
            $gameIds[] = $item->game_id;
        }
        $games = [];
        if (count($gameIds)) {
            $gameList = DB::table('game_data')->whereIn('id', $gameIds)->get();
            foreach ($gameList as $g) {
                $games[$g->id] = $g;
            }
        }
        $dhPlat =  DB::table('dh_platform')
            ->orderBy('id', 'desc')
            ->pluck('title', 'id');
        return view('admin.draw.dhLog', ['draw' => $drawData, 'games' => $games, 'dhPlat'=>$dhPlat]);
    }

}
